var express = require('express');
var exphbs = require('express-handlebars');
var log4js = require('log4js');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs')
var app = express();
var session = require('express-session')
var handlebarHelpers = require('./lib/handlebarHelpers.js')
// view engine setup

//var config = require('./config.js').Config
//var mongoose = require('mongoose')
//mongoose.connect(config.mongo + '/test')
//var files = fs.readdirSync(__dirname + '/models/')
//files.filter(function(file) {
//    return /\.js$/.test(file)
//}).forEach(function(file) {
//    file = file.replace(/\.js$/, '')
//    console.log(file)
//    mongoose.model(file, require('./models/' + file))
//})

if (app.get('env') === 'production') {
    console.log('production.....')
    log4js.configure(config.logConfig)
    app.use(log4js.connectLogger(log4js.getLogger("http"), {level: 'auto'}));
}

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/js', express.static(path.join(__dirname, '/public/javascripts')))
app.use('/css', express.static(path.join(__dirname, '/public/stylesheets')))
app.use(session({
    cookie: {maxAge: (1000 * 3600 * 24 * 30)},
    secret: 'weihao'
}))
var hbs = exphbs.create({
    helpers: handlebarHelpers
});
app.set('views', path.join(__dirname, 'views'));
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
require('./controllers/router')(app)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
